/**
 * Created by Julia on 2016/05/04.
 */
define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'model/project', 'dateUtils', 'appMessageBox'], function ($, domReady, appLocalStorage, appConst, global, project, dateUtils, msgBox) {
    var searchFields = {};
    // var search_btn_key = appConst.searchKey.search_dataImport_btn_key + global.getUserId();
    var search_timeout_key = appConst.searchKey.search_dataImport_timeout_key + global.getUserId();
    // var search_process_key = appConst.searchKey.search_dataImport_process_key + global.getUserId();
    var search_project_key = appConst.searchKey.search_dataImport_project_key + global.getUserId();
    var that;
    return {
        init: function () {
            that = this;
        },
        getSearchFields: function () {
            return searchFields;
        },
        setSearchFields: function (obj) {
            searchFields = {};
            $.extend(searchFields, obj);
        },
        initEvent: function () {
            project.searchProject(null, function (data) {
                that.initSelect(data);

                var queryParameter = appLocalStorage.getLocal(search_project_key);
                if (queryParameter != null) {
                    queryParameter = JSON.parse(queryParameter);

                    var projectIdCache = queryParameter.search_projectId;
                    if (projectIdCache != "" && projectIdCache != null) {
                        $("#sproject").select2("val", projectIdCache);
                    }
                }

                var projectId = global.getCurrentProject();
                if (projectId != "" && projectId != null) {
                    $("#sproject").select2("val", projectId);
                }
            });

            // var queryParameter = appLocalStorage.getLocal(search_btn_key);
            // if (queryParameter != null) {
            //     queryParameter = JSON.parse(queryParameter);
            //
            //     var disabled = queryParameter.disabled;
            //     if (disabled != "" && disabled != null) {
            //         $('#btn_submit').attr('disabled',disabled);
            //     } else {
            //         $('#btn_submit').removeAttr("disabled");
            //     }
            // } else {
            //     $('#btn_submit').removeAttr("disabled");
            // }

            // var queryParameter = appLocalStorage.getLocal(search_process_key);
            // if (queryParameter != null) {
            //     queryParameter = JSON.parse(queryParameter);
            //     var process = queryParameter.process;
            //     if (process != "" && process != null) {
            //         $('#processbar').attr("aria-valuenow", process);
            //         $('#processbar').css('width', process + '' + '%');
            //         $('#p_operator').html($.i18n.prop('DATAIMPORT_ON_OPERATING', process));
            //     } else {
            //         $('#processbar').attr("aria-valuenow", 0);
            //     }
            //     var status = queryParameter.status;
            //     if (status != "" && status != null) {
            //         $('#p_status').append(status);
            //     } else {
            //         $('#p_status').empty();
            //     }
            // } else {
            //     $('#processbar').attr("aria-valuenow", 0);
            // }

            // var queryParameter = appLocalStorage.getLocal(search_timeout_key);
            // if (queryParameter != null) {
            //     queryParameter = JSON.parse(queryParameter);
            //     var timeout = queryParameter.timeout;
            //     if (timeout != "" && timeout != null) {
            //         clearTimeout(timeout);
            //     }
            //     var totalTime = queryParameter.totalTime;
            //     if (totalTime != "" && totalTime != null) {
            //         that.timedCount(totalTime);
            //     }
            // }

            $('#btn_submit').click(function () {
                $("#dataImportTab a:last").tab('show');
                var filePath = $('#filePath').val();
                if (filePath == "") {
                    $('#err_alert').fadeIn(200);
                    return false;
                }
                var fileTypes = ["csv"];
                //var fileTypes = ["csv", "xls", "xlsx"];
                var fileType = filePath.substring(filePath.lastIndexOf('.') + 1);
                if ($.inArray(fileType.toLocaleLowerCase(), fileTypes) == -1) {
                    $('#err_alert').fadeIn(200);
                    return false;
                }

                if ($("#sproject").select2("val") == "") {
                    $('#err_alert').fadeIn(200);
                    return false;
                }

                that.checkTestFile(function (data) {
                    that.clean();
                    if(data.code == 0){
                        msgBox.errorBox(data.message);
                        return false;
                    }
                    if (data.body) {
                        msgBox.errorBox('EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS', that.getFileName());
                    } else {
                        $('#btn_submit').button('loading');
                        // $('#btn_submit').attr('disabled',"true");
                        // var obj = {};
                        // obj["disabled"] = "true";
                        // appLocalStorage.setLocal(search_btn_key, JSON.stringify(obj));
                        that.timedCount(0);
                        $('#uploadForm').submit();
                    }
                });

            });
        },
        getFileName: function () {
            var path = $('#filePath').val();
            var pos1 = path.lastIndexOf('/');
            var pos2 = path.lastIndexOf('\\');
            var pos = Math.max(pos1, pos2);
            return pos < 0 ? path : path.substring(pos + 1);
        },
        timedCount: function(c) {
            var time = dateUtils.second_to_date(c);
            $('#p_time').html(time);
            c=c+1;
            var timeout=setTimeout(function(){that.timedCount(c);},1000);
            that.setBtnAndTime(c, timeout);
            return timeout;
        },
        setBtnAndTime: function(timedCount, timeout) {
            var obj = {};
            obj["totalTime"] = timedCount;
            obj["timeout"] = timeout;
            appLocalStorage.setLocal(search_timeout_key, JSON.stringify(obj));
        },
        checkTestFile: function (callback) {
            $.ajax({
                url: 'data/checkTestFile',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    search_originalName: that.getFileName(),
                    search_projectId: $("#sproject").select2("val")
                },
                success: function (data) {
                    callback(data);
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initSelect: function (data) {
            $("#sproject").select2({
                id: function (rs) {
                    return rs.id;
                },
                //allowClear: true,
                data: {results: data, text: 'name'},
                formatResult: function (data) {
                    var itemFmt = "<span>" + data.name + "</span>";
                    return itemFmt;
                },
                formatSelection: function (data) {

                    $("#dataImportTab a:first").tab('show');
                    var searchparam = {
                        'search_projectId': data.id
                    };
                    that.setSearchFields(searchparam);
                    appLocalStorage.setLocal(search_project_key, JSON.stringify(searchparam));
                    $('#dt_cpw').DataTable().draw();
                    return data.name;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
        },
        clean: function () {
            $('#p_logArea').empty();
            $('#p_operator').html($.i18n.prop('DATAIMPORT_ON_OPERATING', 0));
            $('#processbar').attr("aria-valuenow", 0);
            $('#processbar').removeClass('progress-bar-danger');
            $('#processbar').removeClass('progress-bar-success');
            $('#processbar').removeClass('progress-bar');
            $('#processbar').css('width', '0%');
            $('#p_status').empty();
            $('#err_alert').fadeOut(200);
            $('#p_time').empty();

        }
    }
});

